﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class StoredProcedureCheckCursors : IssueTypeCheckBase
    {
        public StoredProcedureCheckCursors()
        {
            IssueTypeId = 7001;
        }

        public override void Check()
        {
            try
            {
                // Create a Data Context 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;

                var qry = from sp in dc.StoredProcedures
                          where sp.Text.ToUpper().Contains("CURSOR")
                          select sp;


                foreach (var stProc in qry)
                {
                    
                    //Get Issuetype object

                    issue = new Issue();

                    //Get Issuetype object  And Create a new  Global issue object 
                    IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                    issue.IssueType = issueType;
                    issue.TargetId = stProc.StoredProcedureID;
                    issue.Description = issueType.Description.Replace("{StoredProcedureName}", stProc.Name);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }



    }
}
